package com.seari.custody.service.Impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import com.google.api.client.util.Lists;
import com.seari.custody.bean.MeetingFile;
import com.seari.custody.bean.MeetingFileExample;
import com.seari.custody.bean.MeetingVoiceDTO;
import com.seari.custody.component.MinIoUtil;
import com.seari.custody.enums.MeetingFileType;
import com.seari.custody.mapper.MeetingFileMapper;
import com.seari.custody.service.MeetingFileService;
import io.minio.errors.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamSource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.xmlpull.v1.XmlPullParserException;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class MeetingFileServiceImpl implements MeetingFileService {
    public static final String COMMON = "1";
    public static final String DELETED = "0";
    @Autowired
    private MeetingFileMapper meetingFileMapper;
    @Autowired
    private MinIoUtil minIoUtil;

    @Override
    public MeetingFile downloadMeetingFile(String type, String meetingId) {
        MeetingFileExample meetingFileExample = new MeetingFileExample();
        meetingFileExample.createCriteria().andMeetingIdEqualTo(meetingId).andFileTypeEqualTo(type).andDeletedEqualTo(COMMON);
        meetingFileExample.setOrderByClause("create_time desc");
        List<MeetingFile> meetingFiles = meetingFileMapper.selectByExample(meetingFileExample);
        if (CollectionUtil.isNotEmpty(meetingFiles)) {
            return meetingFiles.get(0);
        }
        return null;
    }

    @Override
    public MeetingFile qryMeetingFileById(String id) {
        return meetingFileMapper.selectByPrimaryKey(id);
    }

    @Override
    public void uploadFile(MeetingFile meetingFile) {
        meetingFileMapper.insertSelective(meetingFile);
    }

    @Override
    public List<MeetingFile> qryByMeetingId(String meetingId) {
        MeetingFileExample meetingFileExample = new MeetingFileExample();

        meetingFileExample.createCriteria().andMeetingIdEqualTo(meetingId).andDeletedEqualTo(COMMON);
        return meetingFileMapper.selectByExample(meetingFileExample);
    }

    @Override
    public List<MeetingFile> qryByMeetingIdAndType(String meetingId, MeetingFileType meetingFileType) {
        MeetingFileExample meetingFileExample = new MeetingFileExample();

        meetingFileExample.createCriteria().andMeetingIdEqualTo(meetingId).andDeletedEqualTo(COMMON).andFileTypeEqualTo(meetingFileType.getCode());
        meetingFileExample.setOrderByClause("create_time desc");
        return meetingFileMapper.selectByExample(meetingFileExample);
    }

    @Override
    public Integer delete(String id) {
        MeetingFile meetingFile = new MeetingFile();
        meetingFile.setId(id);
        meetingFile.setDeleted("0");
        return meetingFileMapper.updateByPrimaryKeySelective(meetingFile);
    }

    @Override
    public List<MeetingVoiceDTO> getVoices(String meetingId) {
        MeetingFileExample meetingFileExample = new MeetingFileExample();
        meetingFileExample.createCriteria().andMeetingIdEqualTo(meetingId).andDeletedEqualTo(COMMON).andFileTypeEqualTo(MeetingFileType.MEETING_VOICE.getCode());
        List<MeetingFile> meetingFiles = meetingFileMapper.selectByExample(meetingFileExample);
        if (CollectionUtil.isNotEmpty(meetingFiles)) {
            List<MeetingVoiceDTO> objects = Lists.newArrayListWithCapacity(meetingFiles.size());
            for (MeetingFile meetingFile : meetingFiles) {

                MeetingVoiceDTO meetingVoiceDTO = new MeetingVoiceDTO();
                String textPath = meetingFile.getFilePath();

                File tempFile = FileUtil.createTempFile(new File(new ClassPathResource(".").getPath()));

                try {
                    minIoUtil.getObject(MinIoUtil.MEETING_BUCKET, textPath, tempFile.getAbsolutePath());

                    meetingVoiceDTO.setText(FileUtil.readString(tempFile, StandardCharsets.UTF_8));

                } catch (Exception e) {
                    log.error(e.getMessage());
                } finally {
                    FileUtil.del(tempFile);
                }
                //视频 音频 文字 id是一样的
                String voicePath = textPath.replace("txt", "wav");
                meetingVoiceDTO.setVoice(minIoUtil.genShareLink(MinIoUtil.MEETING_BUCKET, voicePath));

                meetingVoiceDTO.setId(meetingFile.getId());
                objects.add(meetingVoiceDTO);
            }
            return objects;
        }

        return null;
    }

    @SneakyThrows
    @Override
    public void updateMeetingSummary(String id, String data) {
        MeetingFile meetingFile1 = meetingFileMapper.selectByPrimaryKey(id);
        String filePath = meetingFile1.getFilePath();
        minIoUtil.removeObject(MinIoUtil.MEETING_BUCKET, filePath);

        InputStreamSource inputStreamSource = new ByteArrayResource(data.getBytes(StandardCharsets.UTF_8));
        minIoUtil.putObject(MinIoUtil.MEETING_BUCKET, filePath, inputStreamSource.getInputStream());
    }

    @Override
    public Integer delByMeetingIdAndFileType(String meetingId, MeetingFileType meetingFileType) {
        MeetingFileExample meetingFileExample = new MeetingFileExample();
        meetingFileExample.createCriteria().andFileTypeEqualTo(meetingFileType.getCode()).andMeetingIdEqualTo(meetingId);
        MeetingFile meetingFile = new MeetingFile();
        meetingFile.setDeleted(DELETED);
        int i = meetingFileMapper.updateByExampleSelective(meetingFile, meetingFileExample);
        return i;
    }

    @Override
    public Integer delByMeetingId(String meetingId) {
        MeetingFileExample meetingFileExample = new MeetingFileExample();
        meetingFileExample.createCriteria().andMeetingIdEqualTo(meetingId);
        MeetingFile meetingFile = new MeetingFile();
        meetingFile.setDeleted(DELETED);
        int i = meetingFileMapper.updateByExampleSelective(meetingFile, meetingFileExample);
        return i;
    }

    @Override
    public Integer updMeetingFileById(MeetingFile meetingFile) {

        return meetingFileMapper.updateByPrimaryKeySelective(meetingFile);

    }


    public static void main(String[] args) throws
            IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, InvalidArgumentException, InternalException, NoResponseException, InvalidBucketNameException, XmlPullParserException, ErrorResponseException {
//        InputStream inputStream = MinioUtils.getInstance().getObject(MinioUtils.MEEING_BUCKET, "4cb2385fbb464fbda48f0a34789ac204.docx");
//
//
//        System.out.println(inputStream.available());

        String s = "a.docx";
        String type = FileTypeUtil.getType(s);
        System.out.println(type);


    }
}
